import pyglet
from pyglet.gl  import *
from pyglet.window import key
import data

class Editor(pyglet.window.Window):
    def __init__(self):
        super(Editor, self).__init__(800,600)
        self.background = pyglet.image.load(data.filepath('editormap.png')).get_texture()
        self.hero = pyglet.image.load(data.filepath('hero.png')).get_texture()
        self.enemy = pyglet.image.load(data.filepath('e2.png')).get_texture()
        self.pick = pyglet.image.load(data.filepath('pickup.png')).get_texture()
        self.enemy_list = []
        self.pick_list = []
        self.hero = ()
        glEnable(GL_TEXTURE_2D)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        self.mode = 'p'

    def on_mouse_release(self, x, y, button, modifiers):
        if self.mode == 'e':
            self.enemy_list.append((x,y))
        elif self.mode == 'p':
            self.pick_list.append((x,y))
        elif self.mode == 'h':
            self.pick_list.append((x,y))

    def on_key_press(self, symbol, modifiers):
        if symbol == key.E:
            self.mode = 'e'
        elif symbol == key.P:
            self.mode = 'p'
        elif symbol == key.H:
            self.mode = 'h'
        elif symbol == key.SPACE:
            self.pick_list = []
            self.enemy_list = []

        elif symbol == key.S:
            fp = open('level.txt', "w")
            fp.write("%d\n" % len(self.pick_list))
            for pos in self.pick_list:
                fp.write("%d %d\n" % (pos[0]-400, pos[1]-300))
            fp.write("%d\n" % len(self.enemy_list))
            for pos in self.enemy_list:
                fp.write("%d %d\n" % (pos[0]-400, pos[1]-300))
            fp.close()

    def drawRect(self, pos, w):
        glBegin(GL_POLYGON)
        glTexCoord2f(0, 0)
        glVertex2f(pos[0]-w, pos[1]-w)
        glTexCoord2f(0, 1)
        glVertex2f(pos[0]-w, pos[1]+w)
        glTexCoord2f(1, 1)
        glVertex2f(pos[0]+w, pos[1]+w)
        glTexCoord2f(1, 0)
        glVertex2f(pos[0]+w, pos[1]-w)
        glEnd()

    def on_draw(self):
        self.clear()
        glBindTexture(GL_TEXTURE_2D, self.background.id)
        self.drawRect((400, 300), 200)
        glBindTexture(GL_TEXTURE_2D, self.enemy.id)
        for enemy in self.enemy_list:
            self.drawRect(enemy, 15)
        glBindTexture(GL_TEXTURE_2D, self.pick.id)
        for pick in self.pick_list:
            self.drawRect(pick, 10)


if __name__ == '__main__':
    window = Editor()
    pyglet.app.run()
